package net.micode.notes.ui;
/**
 * ChatGpt.java
 * 
 * 注意：如果单独运行该文件，需在 app 的 build.gradle 中添加以下依赖：
 * implementation 'org.json:json:20210307'
 * !! 安卓开发包已经提供此依赖，故无需额外修改项目配置文件。 !!
 * 
 * OpenAI API 使用时偶有几率出现不响应的情况，可以 在调用函数时自行设置强制退出时间或取消按钮。
 * 接口调用方法参见注释与 main 方法（已注释）示例。
 * 
 */

import android.util.Log;

import java.util.TreeMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;

import java.net.URI;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONObject;
import com.google.gson.Gson;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

public final class ChatGpt {
    private static class GptRequest {
        public static class RequestBody {
            public String model;
            public List<Map<String, String>> messages;

            public RequestBody(String model, List<Map<String, String>> messages) {
                this.model = model;
                this.messages = messages;
            }

            public String getModel() {
                return model;
            }

            public List<Map<String, String>> getMessages() {
                return messages;
            }
        }

        private final String hint = "You should follow the assistant to finish the writing task based on user's content.";
        private final String model = "gpt-4-1106-preview";
        private String prompt;
        private String content;

        public GptRequest(String content, String prompt) {
            this.content = content;
            this.prompt = prompt;
        }

//        public GptRequest(String content) {
//            this.content = content;
//            this.prompt = "Continue writing without repeating.";
//        }

        public String toString() {
            List<Map<String, String>> messages = new ArrayList<>();
//            messages.add(new TreeMap<String, String>() {
//                {
//                    put("role", "system");
//                    put("content", hint);
//                }
//            });
            messages.add(new TreeMap<String, String>() {
                {
                    put("role", "user");
                    put("content", prompt + content);
                }
            });
//            messages.add(new TreeMap<String, String>() {
//                {
//                    put("role", "assistant");
//                    put("content", prompt);
//                }
//            });
            RequestBody body = new RequestBody(model, messages);
            return new Gson().toJson(body);
        }
    }

    /** 使用指定的便签内容和提示词进行任务。
     * 
     * @param content 便签内容的字符串（请调用者限制长度在 1000 字符以内）。
     * @param prompt 生成结果。
     * @return
     */
    public static String task(String content, String prompt) {
        final String[] retval = {""};
        Log.d("GPT", "task: Start with: " + retval[0]);
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
//                    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
//                        public boolean verify(String hostname, SSLSession session) {
//                            return true;
//                        }
//                    });
                    GptRequest gptRequest = new GptRequest(content, prompt);
                    URL url = new URL("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token=24.3fd45ca5f8db4619a6348bb58ae71c25.2592000.1705075948.282335-44922766");//("https://api.openai.com/v1/chat/completions");
                    HttpsURLConnection service_conn = (HttpsURLConnection) url.openConnection();
                    service_conn.setRequestMethod("POST");
                    service_conn.setRequestProperty("Content-Type", "application/json");
//                    service_conn.setRequestProperty("Authorization", "Bearer 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");
                    service_conn.setDoOutput(true);
                    DataOutputStream wr = new DataOutputStream(service_conn.getOutputStream());
                    wr.writeBytes(gptRequest.toString());
                    wr.flush();
                    wr.close();
                    Log.i("GPT", "task: Sending 'POST' request");
                    int responseCode = service_conn.getResponseCode();
                    Log.i("GPT", "task: Response Code : " + responseCode);
                    BufferedReader in = new BufferedReader(new InputStreamReader(service_conn.getInputStream()));
                    String inputLine;
                    StringBuffer response = new StringBuffer();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
//                    Log.i("GPT", "response: " + response.toString());
                    JSONObject obj = new JSONObject(response.toString());
                    retval[0] = obj.getString("result");
//                    JSONArray choices = obj.getJSONArray("choices");
//                    for (int i = 0; i < choices.length(); i++) {
//                        JSONObject choice = choices.getJSONObject(i);
//                        if (choice.getInt("index") == 0) {
//                            JSONObject message = choice.getJSONObject("message");
//                            retval[0] = message.getString("content");
//                            break;
//                        }
//                    }

                } catch (Exception e) {
                    retval[0] = e.toString();
                }
            }
        });
        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.i("GPT", "finish with: " + retval[0]);
        return retval[0];
    }
//    public static String task(String content, String prompt) {
//        GptRequest gptRequest = new GptRequest(content, prompt);
//        String retval = "";
//        HttpClient client = HttpClient.newHttpClient();
//        try {
//            HttpRequest request = HttpRequest.newBuilder()
//                .uri(new URI("https://api.openai.com/v1/chat/completions"))
//                .header("Content-Type", "application/json") // 添加头部
//                .header("Authorization", "Bearer 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") // 添加头部
//                .POST(HttpRequest.BodyPublishers.ofString(gptRequest.toString(), StandardCharsets.UTF_8)) // 设置请求方法为 POST 并添加数据
//                .build();
//            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
//            JSONObject obj = new JSONObject(response.body());
//            JSONArray choices = obj.getJSONArray("choices");
//            for (int i = 0; i < choices.length(); i++) {
//                JSONObject choice = choices.getJSONObject(i);
//                if (choice.getInt("index") == 0) {
//                    JSONObject message = choice.getJSONObject("message");
//                    retval = message.getString("content");
//                    break;
//                }
//            }
//        } catch (Exception e) {
//            retval = e.toString();
//        }
//        return retval;
//    }
    
    /** 使用指定的便签内容进行补全。
     * 
     * @param content 便签内容的字符串（请调用者限制长度在 1000 字符以内）。
     * @return 生成内容。
     */
    public static String completion(String content) {
        return task(content, "Continue writing without repeating existing content.");
    }

    // public static void main(String[] args) {
    //     String content = "Naples gives birth to many great tailors. ";
    //     System.out.println("[CONTENT]\n" + content);
    //     String result = completion(content);
    //     System.out.println("[COMPLETION]\n" + content + result);
    //     System.out.println("[ABSTRACT]\n" + task(content + result, "Write a sentence about the content above."));
    // }
}

